package com.hong.serviceuser.service.impl;

import com.alibaba.excel.util.StringUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hong.commonutil.exception.YyghException;
import com.hong.commonutil.helper.JwtHelper;
import com.hong.commonutil.result.ResultCodeEnum;
import com.hong.model.enums.AuthStatusEnum;
import com.hong.model.model.user.Patient;
import com.hong.model.model.user.UserInfo;
import com.hong.model.vo.user.LoginVo;
import com.hong.model.vo.user.UserAuthVo;
import com.hong.model.vo.user.UserInfoQueryVo;
import com.hong.rabbitutil.constant.MqConst;
import com.hong.rabbitutil.service.RabbitService;
import com.hong.serviceuser.mapper.UserInfoMapper;
import com.hong.serviceuser.service.PatientService;
import com.hong.serviceuser.service.UserInfoService;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

@Service
public class UserInfoServiceImpl extends ServiceImpl<UserInfoMapper, UserInfo> implements UserInfoService {
    @Autowired
    private UserInfoMapper userInfoMapper;
    @Autowired
    private PatientService patientService;
    @Autowired
    private RedisTemplate<String,String> redisTemplate;
    @Autowired
    private RabbitService rabbitService;
    @Override
    public Map<String, Object> login(LoginVo loginVo) {
        //获取手机号和验证码
        String phone = loginVo.getPhone();
        String code = loginVo.getCode();
        //先判断手机号和验证码是否为空
        if (StringUtils.isEmpty(phone) || StringUtils.isEmpty(code)) {
            throw new YyghException(ResultCodeEnum.PARAM_ERROR);
        }
        //验证手机验证码是否和输入的验证码一致
        String trueCode = redisTemplate.opsForValue().get(phone);
        if(!StringUtils.isEmpty(trueCode)&&!code.equals(trueCode)){
            throw new YyghException(ResultCodeEnum.CODE_ERROR);
        }
        //判断是否是第一次登录(如果数据库存在手机号的话就不是第一次登录)
        UserInfo userInfo = userInfoMapper.selectByPhone(phone);
        if (userInfo == null) {
            userInfo = new UserInfo();
            userInfo.setName("");
            userInfo.setStatus(1);
            userInfo.setPhone(phone);
            baseMapper.insert(userInfo);
        }
        //检测是否被禁用
        if (userInfo.getStatus() == 0) {
            throw new YyghException(ResultCodeEnum.LOGIN_DISABLED_ERROR);
        }
        //返回页面显示名称
        Map<String, Object> map = new HashMap<>();
        String name = userInfo.getName();
        if (StringUtils.isEmpty(name)) {
            name = userInfo.getNickName();
        }
        if (StringUtils.isEmpty(name)) {
            name = userInfo.getPhone();
        }
        map.put("name", name);
        //返回登录信息.用户名.token信息
        //生成token
        String token = JwtHelper.createToken(userInfo.getId(), name);
        map.put("token", token);
        return map;
    }
    @Transactional
    @Override
    public void userAuth(Long userId, UserAuthVo userAuthVo) {
        //根据用户id查询用户信息
        UserInfo userInfo = baseMapper.selectById(userId);
        //设置认证信息
        userInfo.setName(userAuthVo.getName());
        userInfo.setCertificatesType(userAuthVo.getCertificatesType());
        userInfo.setCertificatesNo(userAuthVo.getCertificatesNo());
        userInfo.setCertificatesUrl(userAuthVo.getCertificatesUrl());
        userInfo.setAuthStatus(AuthStatusEnum.AUTH_RUN.getStatus());
        //进行信息更新
        rabbitService.sendMessage(MqConst.EXCHANGE_DIRECT_USER,MqConst.ROUTING_USER_ITEM,userInfo);
    }

    @Override
    public UserInfo getById(long id) {
        return baseMapper.selectById(id);
    }

    @Override
    public IPage<UserInfo> selectPage(Page<UserInfo> pageParm, UserInfoQueryVo userInfoQueryVo) {
        //获取条件值，如果非空就加上该条件
        String name = userInfoQueryVo.getKeyword();  //用户名称
        Integer status = userInfoQueryVo.getStatus();//用户状态
        Integer authStatus = userInfoQueryVo.getAuthStatus();//认证状态
        String createTimeBegin = userInfoQueryVo.getCreateTimeBegin();//开始时间
        String createTimeEnd = userInfoQueryVo.getCreateTimeEnd();//结束时间
        QueryWrapper<UserInfo> queryWrapper=new QueryWrapper<>();
        if(!StringUtils.isEmpty(name)) {
            queryWrapper.like("name",name);
        }
        if(!StringUtils.isEmpty(status)) {
            queryWrapper.eq("status",status);
        }
        if(!StringUtils.isEmpty(authStatus)) {
            queryWrapper.eq("auth_status",authStatus);
        }
        if(!StringUtils.isEmpty(createTimeBegin)) {
            queryWrapper.ge("create_time",createTimeBegin);
        }
        //条件查询，begin -> end 这个区间创建的用户
        if(!StringUtils.isEmpty(createTimeEnd)) {
            queryWrapper.le("create_time",createTimeEnd);
        }
        //调用mapper方法
        Page<UserInfo> pages = baseMapper.selectPage(pageParm, queryWrapper);
        //编号变成对应值的封装
        pages.getRecords().stream().forEach(item ->{
            this.packageUserInfo(item);
        });
        return pages;
    }

    @Override
    public void lock(long userId, Integer status) {
        if(status==0||status==1){
            baseMapper.updateStatus(userId,status);
        }
    }

    @Override
    public Map<String, Object> show(Long userId) {
        Map<String,Object> res = new HashMap<>();
        UserInfo userInfo=this.packageUserInfo(baseMapper.selectById(userId));
        res.put("userInfo",userInfo);
        List<Patient> patients = patientService.findAllById(userId);
        res.put("patientList",patients);
        return res;
    }

    /**
     * @param userId
     * @param authStatus  为2表示通过，为-1表示不通过
     */
    @Override
    public void approval(Long userId, Integer authStatus) {
        if(authStatus==-1||authStatus==2){
            UserInfo userInfo=baseMapper.selectById(userId);
            userInfo.setAuthStatus(authStatus);
            userInfoMapper.updateById(userInfo);
        }
    }

    /**
     * 根据用户认证的姓名，模糊查询叫该用户的所用用户列表
     * @param username
     * @return
     */
    @Override
    public List<UserInfo> findUserListByUserName(String username) {
        QueryWrapper<UserInfo> wrapper = new QueryWrapper<>();
        wrapper.like("name",username);
        List<UserInfo> userInfoList = baseMapper.selectList(wrapper);
        return userInfoList;
    }

    /**
     * 将编号变成对应着的封装，例如status = 0代表锁定
     * @param userInfo
     * @return
     */
    private UserInfo packageUserInfo(UserInfo userInfo){
        //处理认证状态编码
        userInfo.getParam().put("authStatusString", AuthStatusEnum.getStatusNameByStatus(userInfo.getAuthStatus()));
        //处理用户状态
        String statusString =  userInfo.getStatus().intValue()==0?"锁定":"正常";
        userInfo.getParam().put("statusString",statusString);
        return userInfo;
    }
}
